﻿#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    BaseEditor(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    table=ST_UNIT_PARTS;
    itemModel=new QStandardItemModel(this);
    ui->tableView->setModel(itemModel);
    ui->tableView->setEditTriggers(QTableView::NoEditTriggers);
    updateUnits();
    createMenu();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::generateMenu()
{
    menu->addAction(QStringLiteral("配件一览"),this,&Widget::showManager);
    menu->addSeparator();
    menu->addAction(QStringLiteral("添加单元..."),this,&Widget::newItem);
}

void Widget::showManager()
{
    UnitManager manager;
    manager.exec();
}

void Widget::newItem()
{
    AddItem addItem;
    addItem.exec();
}

void Widget::updateUnits()
{
    if(ui->units->count() != 0)
        ui->units->clear();

    QStringList items=sp_getCategory("label",table);
    if(!items.isEmpty())
    {
        ui->units->addItems(items);
        ui->units->setCurrentIndex(-1);
    }
}

void Widget::on_piece_returnPressed()
{
    QString label=ui->units->currentText();
    QString pieceStr=ui->piece->text().trimmed();
    if(label.isEmpty() || pieceStr.isEmpty())
        return;

    bool ok;
    int piece=pieceStr.toInt(&ok);
    if(!ok)
    {
        QMessageBox::warning(this,QStringLiteral("异常情况"),
                             QStringLiteral("输入无效！"));
        return;
    }

    if(itemModel->rowCount() != 0)
        itemModel->clear();

    QSqlQuery query;
    query.exec(QString("select name,number,remark from %1 where label='%2'")
               .arg(table).arg(label));
    while (query.next()) {
        QString name=query.value(0).toString();
        int number=query.value(1).toInt();
        QString remark=query.value(2).toString();
        QList<QStandardItem *> item;
        item.append(new QStandardItem(name));
        item.append(new QStandardItem(QString::number(piece * number)));
        item.append(new QStandardItem(remark));
        itemModel->appendRow(item);
    }

    if(itemModel->rowCount() > 0)
    {
        itemModel->setHeaderData(0,Qt::Horizontal,QStringLiteral("配件名称"));
        ui->tableView->setColumnWidth(0,240);
        itemModel->setHeaderData(1,Qt::Horizontal,QStringLiteral("配件数量"));
        itemModel->setHeaderData(2,Qt::Horizontal,QStringLiteral("附加说明"));
    }
}
